//
//  UITextView+inputAccessry.m
//

#import "UITextView+inputAccessry.h"
#import <objc/runtime.h>
#import "UIColor+Expanded.h"
#import "UIView+Frame.h"
#import "UIView+Corner.h"
#import "UIButton+ExpandButton.h"
#import "Masonry.h"

@implementation UITextView (inputAccessry)

static const char PointView = '\0';
- (void)setPointView:(UIView *)pointView{
    
    objc_setAssociatedObject(self, &PointView, pointView, OBJC_ASSOCIATION_ASSIGN);
}

- (UIView *)pointView{
    
    return objc_getAssociatedObject(self, &PointView);
}

static const char PlaceholderColor = '\0';
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    UILabel *placeholderText = [self.superview viewWithTag:10000];
    if(placeholderText) placeholderText.textColor = [UIColor colorWithRGBHexString:@"BBBBBB"];
    objc_setAssociatedObject(self, &PlaceholderColor, placeholderColor, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (UIColor *)placeholderColor {
    return objc_getAssociatedObject(self, &PlaceholderColor);
}

static const char Placeholder = '\0';
- (void)setPlaceholder:(NSString *)placeholder{
    objc_setAssociatedObject(self, &Placeholder, placeholder, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [self addPlaceholderText:placeholder];
}

- (NSString *)placeholder{

    return objc_getAssociatedObject(self, &Placeholder);
}

- (void)addPlaceholderText:(NSString *)placeholder{
    
    UILabel *placeholderText = [self.superview viewWithTag:10000];
    if(!placeholderText) {
        placeholderText = [[UILabel alloc] init];
        [self.superview addSubview:placeholderText];
        
        CGFloat offsetValue  = self.space.floatValue;
        
        __weak typeof(self) weakSelf = self;
        [placeholderText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.mas_top).offset(offsetValue);
            make.leading.equalTo(weakSelf.mas_leading).offset(offsetValue);
            make.height.equalTo(@(weakSelf.font.lineHeight));
        }];
    }
    placeholderText.font = self.font;
    placeholderText.tag = 10000;
    placeholderText.textColor = [UIColor colorWithRGBHexString:@"BBBBBB"];
    placeholderText.text = placeholder;
    [self addObserverTextViewDidChange];
}

- (void)updateContent {
    UILabel *placeholderText = [self.superview viewWithTag:10000];
    placeholderText.hidden = self.text.length;
    
    CGFloat offsetValue  = self.space.floatValue;
    __weak typeof(self) weakSelf = self;
    [placeholderText mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.mas_top).offset(offsetValue);
        make.leading.equalTo(weakSelf.mas_leading).offset(offsetValue);
        make.height.equalTo(@(weakSelf.font.lineHeight));
    }];
}

static const char ContentOffsetView = '\0';
- (void)setContentOffsetView:(UIView *)contentOffsetView{
    
    objc_setAssociatedObject(self, &ContentOffsetView, contentOffsetView, OBJC_ASSOCIATION_ASSIGN);
}

- (UIView *)contentOffsetView{
    
    return objc_getAssociatedObject(self, &ContentOffsetView);
}


static const char InitialPosition = '\0';
- (void)setInitialPosition:(NSNumber *)initialPosition{
    
    objc_setAssociatedObject(self, &InitialPosition, initialPosition, OBJC_ASSOCIATION_ASSIGN);
}

- (NSNumber *)initialPosition{
    
    return objc_getAssociatedObject(self, &InitialPosition);
}

static const char OldStartPosition = '\0';
- (void)setOldStartPosition:(NSNumber *)oldStartPosition{
    
    objc_setAssociatedObject(self, &OldStartPosition, oldStartPosition, OBJC_ASSOCIATION_ASSIGN);
}

- (NSNumber *)oldStartPosition{
    
    return objc_getAssociatedObject(self, &OldStartPosition);
}


static const char Space = '\0';

- (void)setSpace:(NSNumber *)space {
    objc_setAssociatedObject(self, &Space, space, OBJC_ASSOCIATION_ASSIGN);
    [self updateContent];
}

- (NSNumber *)space {
    return objc_getAssociatedObject(self, &Space);
}

- (void)setShowCustomInputAccessry:(BOOL)showCustomInputAccessry{
    
    if (showCustomInputAccessry&&self.editable) {
        
        UIButton * hiddenbutton =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,40 )];
        [hiddenbutton setTitle:@"Done" forState:UIControlStateNormal];
        [hiddenbutton setTitleColor:[UIColor colorWithRGBHexString:@"555555"] forState:UIControlStateNormal];
        hiddenbutton.titleLabel.font = [UIFont systemFontOfSize:15];
        hiddenbutton.titleLabel.textAlignment = NSTextAlignmentRight;
        hiddenbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [hiddenbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
        
        __weak typeof(self) weakSelf = self;
        [hiddenbutton addClickBlock:^(UIButton * _Nonnull button) {
            [weakSelf resignFirstResponder];
        }];
        self.inputAccessoryView = hiddenbutton;
        self.inputAccessoryView.backgroundColor = [UIColor colorWithRGBHexString:@"eaeaea"];

    }else{
        self.inputAccessoryView =nil;
    }
    
}

- (void)addObserverKeyboard:(UIView *)pointView contentOffsetView:(UIView *)contentOffsetView{
    self.pointView = pointView;
    self.contentOffsetView = contentOffsetView;
    if([contentOffsetView isKindOfClass:[UIScrollView class]]){
        self.oldStartPosition = @(((UIScrollView *)contentOffsetView).contentInset.top);
    }else{
        
    }
    // 添加通知监听见键盘弹出/退出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];

}

// 键盘监听事件
- (void)keyboardAction:(NSNotification*)sender{
    
    if ([self isFirstResponder]) {
       
        UIView * responderView = self.pointView;
        // 通过通知对象获取键盘frame: [value CGRectValue]
        NSDictionary *useInfo = [sender userInfo];
        NSValue *value = [useInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        // <注意>具有约束的控件通过改变约束值进行frame的改变处理
        if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
            
            CGRect frame2 = [responderView convertRect:responderView.bounds toView:nil];

            if ([value CGRectValue].origin.y<(frame2.origin.y+frame2.size.height)) {

                if ([self.contentOffsetView isKindOfClass:[UIScrollView class]]) {
                    UIScrollView * scrollView = (UIScrollView *) self.contentOffsetView;
                    [scrollView setContentOffset:CGPointMake(0, ((frame2.origin.y+frame2.size.height)-[value CGRectValue].origin.y)+scrollView.contentOffset.y)
                                             animated:YES];
                }else {
                    
                    self.initialPosition = @(self.contentOffsetView.y);
                    NSDictionary *userInfo = sender.userInfo;
                    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
                    CGFloat bottom = CGRectGetHeight(keyboardFrame);
                    CGPoint originInWindow = [self.pointView convertPoint:self.pointView.bounds.origin toView:nil];
                    [self.contentOffsetView setFrame:CGRectMake(self.contentOffsetView.x,
                                                                originInWindow.y - self.pointView.height - bottom,
                                                                self.contentOffsetView.width, self.contentOffsetView.height)];
                }
            }
            
        }else if([sender.name isEqualToString:UIKeyboardDidChangeFrameNotification]){
                          
        }else{
            if ([self.contentOffsetView isKindOfClass:[UIScrollView class]]) {
                UIScrollView * scrollView = (UIScrollView *) self.contentOffsetView;
                [scrollView setContentOffset:CGPointMake(0, -self.oldStartPosition.floatValue) animated:YES];
            }else {
                [self.contentOffsetView setFrame:CGRectMake(self.contentOffsetView.x, self.initialPosition.floatValue, self.contentOffsetView.width, self.contentOffsetView.height)];
                
                self.initialPosition = nil;
            }
        }
    }
}

- (void)removeObserverKeyboard{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


static const char TextDidChange = '\0';
- (void)setTextViewDidChange:(TextViewDidChange)textViewDidChange{
    
    objc_setAssociatedObject(self, &TextDidChange,
    textViewDidChange, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (TextViewDidChange)textViewDidChange{
    
    return objc_getAssociatedObject(self, &TextDidChange);
}

static const char TextViewDidEndEdit = '\0';
- (void)setTextViewDidEndEdit:(TextViewDidEndEditing)textViewDidEndEdit{
    
    objc_setAssociatedObject(self, &TextViewDidEndEdit,
                             textViewDidEndEdit, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (TextViewDidEndEditing)textViewDidEndEdit{
    
    return objc_getAssociatedObject(self, &TextViewDidEndEdit);
}

#pragma 处理输入文字长度
static const char MaxLength = '\0';
- (void)setMaxLength:(NSNumber *)maxLength{

    objc_setAssociatedObject(self, &MaxLength,
    maxLength, OBJC_ASSOCIATION_ASSIGN);
}

- (NSNumber *)maxLength{

    return objc_getAssociatedObject(self, &MaxLength);
}


- (void)addObserverTextViewDidChange{
    
    if (!self.maxLength) {
        self.maxLength = @(0xffffff);
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeAction:) name:UITextViewTextDidChangeNotification object:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
}

- (void)textDidEndEditing:(NSNotification * )name {
    if(self.textViewDidEndEdit){
        self.textViewDidEndEdit(self);
    }
}


- (void)textViewDidChangeAction:(NSNotification * )name{

    UITextView* sender = name.object;
    
    if (sender != self) {
        return;
    }
    
    
    NSInteger kMaxLength = self.maxLength.integerValue;

    NSString *toBeString = self.text;

    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage

    if ([lang isEqualToString:@"zh-Hans"]) { //中文输入

        UITextRange *selectedRange = [self markedTextRange];

        //获取高亮部分

        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];

        if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制

            if (toBeString.length > kMaxLength) {

                self.text = [toBeString substringToIndex:kMaxLength];

            }

        }else{//有高亮选择的字符串，则暂不对文字进行统计和限制

        }

    }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况

        if (toBeString.length > kMaxLength) {

            self.text = [toBeString substringToIndex:kMaxLength];

        }
    }

    UILabel *placeholderText = [self.superview viewWithTag:10000];
    placeholderText.hidden = toBeString.length;
    
    if (self.textViewDidChange) {
        self.textViewDidChange(self);
    }
    
}

- (NSInteger)countingHardLineBreaks {
    NSString *string;
    NSInteger numberOfLines, index, stringLength = [self.text length];
    for (index = 0, numberOfLines = 0; index < stringLength;index++){
        string = [self.text substringWithRange:NSMakeRange(index, 1)];
        if([string isEqualToString:@"\r"]||[string isEqualToString:@"\n"])
            numberOfLines += 1;
    }
    return numberOfLines;
}

- (NSInteger)numberOfLines {
    
    NSLayoutManager *layoutManager = [self layoutManager];
    NSInteger numberOfLinesLayout, indexLayout, numberOfGlyphs =
            [layoutManager numberOfGlyphs];
    NSRange lineRange;
    for (numberOfLinesLayout = 0, indexLayout = 0; indexLayout < numberOfGlyphs; numberOfLinesLayout++){
        (void) [layoutManager lineFragmentRectForGlyphAtIndex:indexLayout effectiveRange:&lineRange];
        indexLayout = NSMaxRange(lineRange);
    }
    return numberOfLinesLayout ;
}


@end
